#!/bin/bash

# function to set GPU to performance mode
set_gpu_performance() {
    echo "Setting GPU to performance mode..."
    echo performance > /sys/devices/platform/fb000000.gpu/devfreq/fb000000.gpu/governor
}

# function to enable BT from ap6275p or ap6256
enable_bt() {
    bt_status=$(cat /proc/device-tree/wireless-bluetooth/status | tr -d '\0')
    wifi_chip=$(cat /proc/device-tree/wireless-wlan/wifi_chip_type | tr -d '\0')
    if [[ ${wifi_chip} == "ap6275p" && ${bt_status} == "okay" ]]; then
        echo "Enabling BT from ap6275p..."
        rfkill unblock all
        brcm_patchram_plus --enable_hci --no2bytes --use_baudrate_for_download --tosleep 200000 \
            --baudrate 1500000 --patchram /lib/firmware/ap6275p/BCM4362A2.hcd /dev/ttyS9 &
        echo $! > /var/run/brcm_patchram_plus.pid
    fi
    if [[ ${wifi_chip} == "ap6256" && ${bt_status} == "okay" ]]; then
        echo "Enabling BT from ap6256..."
        rfkill unblock all
        brcm_patchram_plus --enable_hci --no2bytes --use_baudrate_for_download --tosleep 200000 \
            --baudrate 1500000 --patchram /lib/firmware/brcm/BCM4345C5.hcd /dev/ttyS9 &
        echo $! > /var/run/brcm_patchram_plus.pid
    fi
}

# function to add debugfs entry to /etc/fstab and mount it
setup_debugfs() {
    if [ -f /boot/boot/batocera.board ]; then
        BOARD=$(cat /boot/boot/batocera.board)
    else
        BOARD=""
    fi

    if [ "${BOARD}" = "orangepi-5" ] || [ "${BOARD}" = "orangepi-5b" ]; then
        echo "Setting up debugfs for orangepi5..."
        if ! grep -q "debugfs /sys/kernel/debug debugfs nosuid,nodev,noexec 0 0" /etc/fstab; then
            echo "debugfs /sys/kernel/debug debugfs nosuid,nodev,noexec 0 0" >> /etc/fstab
        fi

        mount -a

        echo "Enabling USB 2.0 & USB-C ports..."
        echo host > /sys/kernel/debug/usb/fc000000.usb/mode
    fi
}

# function to stop brcm_patchram_plus process
stop_brcm_patchram() {
    if [ -f /var/run/brcm_patchram_plus.pid ]; then
        PID=$(cat /var/run/brcm_patchram_plus.pid)
        echo "Stopping brcm_patchram_plus process..."
        kill $PID
        rm /var/run/brcm_patchram_plus.pid
        echo "brcm_patchram_plus process stopped."
    fi
}

case "$1" in
    start)
        set_gpu_performance
        enable_bt
        setup_debugfs
        ;;
    stop)
        stop_brcm_patchram
        ;;
    restart)
        stop_brcm_patchram
        set_gpu_performance
        enable_bt
        setup_debugfs
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit 0
